package b1.scenes.fight
{
	import Box2D.Collision.b2Manifold;
	import Box2D.Collision.b2WorldManifold;
	import Box2D.Common.Math.b2Math;
	import Box2D.Common.Math.b2Vec2;
	import Box2D.Dynamics.Contacts.b2Contact;
	import Box2D.Dynamics.b2ContactImpulse;
	import Box2D.Dynamics.b2ContactListener;
	
	import flash.events.*;

	public class ObjectContactListener extends b2ContactListener
	{
		public var eventDispatcher:EventDispatcher;
		private const impuseLimit:Number = 5;
		
		public function ObjectContactListener()
		{
			eventDispatcher = new EventDispatcher(); 
			super();
		}
		
		override public function PreSolve(contact:b2Contact, oldManifold:b2Manifold):void 
		{
            var objectA:Object = contact.GetFixtureA().GetBody().GetUserData();  
            var objectB:Object = contact.GetFixtureB().GetBody().GetUserData();
            var hitShield:Shield;
            var hitBone:Bone;
            if (objectA is Shield && objectB is Bone)
            {
            	hitShield = objectA as Shield;
            	hitBone = objectB as Bone;
            }
            else if (objectB is Shield && objectA is Bone)
            {
            	hitShield = objectB as Shield;
            	hitBone = objectA as Bone;
            }
            if (hitShield != null)
            {
	        	var manifold:b2WorldManifold = new b2WorldManifold();
	        	contact.GetWorldManifold(manifold);
            	var point:b2Vec2 = manifold.m_points[0];
            	if (hitShield.leftFlag && point.x * Fight.worldScale < hitShield.x || 
            		!hitShield.leftFlag && point.x * Fight.worldScale > hitShield.x)
            		contact.SetEnabled(false);
            }
		}
		
		override public function PostSolve(contact:b2Contact, impulse:b2ContactImpulse):void 
		{  
            var objectA:Object = contact.GetFixtureA().GetBody().GetUserData();  
            var objectB:Object = contact.GetFixtureB().GetBody().GetUserData();
            if (objectA is FightObject && objectB is FightObject)
            {
            	//得到最大冲量
				var maxImpulse:Number = 0.0;
				var impulseCount:int = contact.GetManifold().m_pointCount;
				for (var i:int = 0; i < impulseCount; i++)
				{
					maxImpulse = b2Math.Max(maxImpulse, impulse.normalImpulses[i]);
				}
//				trace("maxImpulse: " + maxImpulse);
				if (maxImpulse > impuseLimit)
				{
		            eventDispatcher.dispatchEvent(new ObjectContactEvent(contact, impulse));
		  		}
            }
  		}
	}
}